﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OracleClient;
using System.Collections;

namespace BLL.StatSheme
{
    public class shemeShowResult
    {
        OracleDAL.StatSheme.shemeShowResult oss = new OracleDAL.StatSheme.shemeShowResult();
        /// <summary>
        /// 得到统计项目
        /// </summary>
        /// <param name="sqlWhere"></param>
        /// <returns></returns>
        /// 
        #region 得到统计项目
        public DataSet getList_Operate(string sqlWhere)
        {
            return oss.GetList(sqlWhere);
        }
        #endregion

        ///****************************************************
        ///*函数名称: titleBelong
        ///*功能描述: 得到标题脚本字符串
        ///*参数列表: 1.方案号
        ///*作者    : 
        /// *创建日期: 2009/05
        ///  ************************************************  
        #region 得到标题脚本字符串
        public string titleBelong(string shemeID, string nodeid, string belongOperate,string priView)
        {
            string str;
            string sql = "";
            string resultStr = "";
            string strRecord = "";

            string statNumberTr = "";

            //资源/节点  所跨的行数
            DataSet dsMM = new DataSet();//查出最大最小的 LEVELCODE的长度
            int maxTemp = 0;
            int minTemp = 0;
            int ColHeadLeft = 0;
            int lengthTemp = 0;

            ArrayList arrtd = new ArrayList();
            DataSet dsTitle1 = new DataSet();
            DataSet dsN = new DataSet();
            ArrayList arrN = new ArrayList();//
            ArrayList arrTotalN = new ArrayList();
            DataRow[] drN;
            string strlin = "";
            string strN = "";
            string strArrN = "";

            DataSet ds = new DataSet();  //特级标题记录的全部记录

            ds = oss.GetList("SHEMEID='" + shemeID + "'");



            dsMM = oss.getValue("select max(length(levelcode)) as \"max\",min(length(levelcode)) as \"min\" from com_statistics_sheme_operate where shemeid='" + shemeID + "'");
            if (Convert.ToInt32(dsMM.Tables[0].Rows[0][0].ToString()) == Convert.ToInt32(dsMM.Tables[0].Rows[0][1].ToString()))
            {
                ColHeadLeft = 1;//资源/节点  所跨的行数
            }
            else
            {
                maxTemp = Convert.ToInt32(dsMM.Tables[0].Rows[0][0].ToString());
                minTemp = Convert.ToInt32(dsMM.Tables[0].Rows[0][1].ToString());

                ColHeadLeft = (maxTemp - minTemp) / 2 + 1;//资源/节点  所跨的行数
            }
            //font-size:20px;
            str = "<table bgcolor='#EDF7FF' bordercolor='#86AECE'  cellspacing='0' cellpadding='0' border='1' style='border-collapse :collapse' width=100%>";
            str += "<tr  height=25>";
            str += "<td rowspan=" + ColHeadLeft + " width=15% align=center style='background-color :#EDF7FF'><font color='black'>节点/资源</font></td>";

            sql = " select levelcode from com_statistics_sheme_operate";
            sql += " where  length(levelcode)=(select MIN(length(levelcode)) as max from com_statistics_sheme_operate where shemeid='" + shemeID + "')  and shemeid='" + shemeID + "' order by levelcode";

            dsTitle1 = oss.getValue(sql);//一级标题记录

            if (dsTitle1.Tables[0].Rows.Count != 0)
            {
                for (int indexTN = 0; indexTN < dsTitle1.Tables[0].Rows.Count; indexTN++)// 查处标题项  为1的 
                {
                    sql = "select levelcode as  max from com_statistics_sheme_operate where length(levelcode)= ( select max(length(levelcode))from com_statistics_sheme_operate where levelcode like '" + dsTitle1.Tables[0].Rows[indexTN]["LEVELCODE"] + "%' and shemeid='" + shemeID + "')and levelcode like '" + dsTitle1.Tables[0].Rows[indexTN]["LEVELCODE"] + "%' and shemeid='" + shemeID + "'";
                    strN = oss.getMaxValue(sql);  //查出同一最短  中 的 最长的   9001     9001010101

                    for (int i = (strN.Length - minTemp) / 2; i >= 0; i--)//从最长的中  一次-2 递归回来
                    {
                        // arrN.Clear();
                        lengthTemp = dsTitle1.Tables[0].Rows[indexTN]["LEVELCODE"].ToString().Length + i * 2;
                        sql = "SHEMEID='" + shemeID + "' and LEVELCODE like '" + dsTitle1.Tables[0].Rows[indexTN]["LEVELCODE"] + "%' and length(LEVELCODE) =" + lengthTemp + " order by LEVELCODE";
                        dsN = oss.GetList(sql);// 
                        for (int j = 0; j < dsN.Tables[0].Rows.Count; j++)
                        {
                            //sql = "SHEMEID='" + shemeID + "' and STATTYPE='stat' and LEVELCODE like '" + dsN.Tables[0].Rows[j]["LEVELCODE"] + "%' ";
                            sql = "SHEMEID='" + shemeID + "'and STATTYPE='stat'  and LEVELCODE like '" + dsN.Tables[0].Rows[j]["LEVELCODE"] + "%' ";
                            drN = ds.Tables[0].Select(sql, "LEVELCODE");


                            int tempColSpan = drN.Length;

                            //  int tempRowSpan = maxTemp - (lengthTemp / 2);

                            strRecord = dsN.Tables[0].Rows[j]["STATITEMNAME"].ToString() + "^" + dsN.Tables[0].Rows[j]["LEVELCODE"].ToString() + "^" + dsN.Tables[0].Rows[j]["STATTYPE"].ToString() + "^" + tempColSpan;

                            if (dsN.Tables[0].Rows[j]["STATTYPE"].ToString().Length > 3)
                            {
                                if (dsN.Tables[0].Rows[j]["STATTYPE"].ToString().Substring(0, 4) == "stat")//记录统计项目
                                {
                                    arrN.Add(dsN.Tables[0].Rows[j]["STATITEMNAME"].ToString() + "###" + dsN.Tables[0].Rows[j]["STATCONDITION"].ToString() + "###" + dsN.Tables[0].Rows[j]["LEVELCODE"].ToString() + "###" + dsN.Tables[0].Rows[j]["RESID"].ToString() + "###" + dsN.Tables[0].Rows[j]["STATTYPE"].ToString() + "###" + dsN.Tables[0].Rows[j]["BELONGOPEREAT"].ToString());//记录统计项目的顺序
                                }
                            }

                            if (j == dsN.Tables[0].Rows.Count - 1)
                            {
                                strArrN += strRecord;
                            }
                            else
                            {
                                strArrN += strRecord + "???";
                            }

                        }
                        if (i != 0)
                        {
                            strArrN += "***";
                        }
                        //  arrTotalN.Add(arrN);
                    }
                    if (indexTN != dsTitle1.Tables[0].Rows.Count - 1)
                    {
                        strArrN += "|||";
                    }
                }
                arrtd = getTableDesc(strArrN, maxTemp / 2 - 2);


                resultStr = getTableSheme(arrtd);

                statNumberTr = getStatNumber(ds.Tables[0].Select("SHEMEID='" + shemeID + "' and (STATTYPE='1' or STATTYPE='stat,1')", "LEVELCODE"), arrN, shemeID, nodeid, belongOperate, priView);
            }
            dsN.Clear();
            dsN.Dispose();
            ds.Clear();
            ds.Dispose();
            return str + resultStr + statNumberTr + "</table>";
        }
        #endregion



        //处理链接字符  例如  倒叙回去 


        /*        ***全程数字通道^900101^1^7
        ***通道等级^90010101^yybm^5???通道用途^90010102^yybm^2
        pcm^9001010201^stat^1???人工中继^9001010202^stat^1
        ***一级^9001010101^yybm^2???二级^9001010102^yybm^1???三级^9001010103^stat^1???四级^9001010104^stat^1???
        ***通道用途^900101010101^yybm^2???通道用途^900101010201^yybm^1
        pcm^90010101010101^stat^1???人工中继^90010101010102^stat^1???pcm^90010101020101^stat^1


        ***台站^900102^1^1
        ***台站类\n别^90010201^yybm^1
        |||枢纽站^9001020101^stat^1

        ***C频卫星网地面\n站^900103^1^1
        ***站型^90010301^yybm^1
        |||战备站^9001030101^stat^1 */
        //跨行列合并


        ///****************************************************
        ///*函数名称: getTableDesc
        ///*功能描述: 合并
        ///*参数列表: 1.total字符串 2.行数最大值
        ///*作者    : 
        /// *创建日期: 2009/05
        ///  ************************************************  

        #region 合并
        public ArrayList getTableDesc(string str, int maxcol)
        {
            string[] strTitle1;
            string[] temp1 = { "|||" };


            string[] strTitleN;
            string[] temp2 = { "***" };

            ArrayList arr = new ArrayList();
            if (str != "")
            {
                strTitle1 = str.Split(temp1, StringSplitOptions.None);
                for (int i = 0; i < strTitle1.Length; i++)
                {
                    strTitleN = strTitle1[i].ToString().Split(temp2, StringSplitOptions.None);
                    List<string> descStr = new List<string>();

                    for (int j = strTitleN.Length - 1; j >= 0; j--)
                    {
                        string[] temp3 = { "???" };
                        string[] strW = strTitleN[j].Split(temp3, StringSplitOptions.None);

                        string strTd = "";
                        for (int n = 0; n < strW.Length; n++)
                        {
                            string[] strJ = strW[n].Split('^');

                            //if (strJ[2].Length > 3)
                            //{
                            //    if (strJ[2].Substring(0, 3) == "stat")
                            //    {
                            //        strTd += "<td  align=center rowspan=" + (maxcol - descStr.Count).ToString() + " colspan=" + strJ[3] + ">" + strJ[0] + "</td>";
                            //    }
                            //    else
                            //    {
                            //        strTd += "<td  align=center colspan=" + strJ[3] + ">" + strJ[0] + "</td>";
                            //    }

                            //}
                            //else
                            //{
                            //    strTd += "<td  align=center colspan=" + strJ[3] + ">" + strJ[0] + "</td>";
                            //}

                            if (strJ[2].IndexOf("stat") != -1)
                            {
                                //strTd += "<td rowspan=" + (maxcol - strTitleN.Length-1).ToString() + " colspan=" + strJ[3] + ">" + strJ[0] + "</td>";
                                strTd += "<td  align=center rowspan=" + (maxcol - descStr.Count).ToString() + " colspan=" + strJ[3] + "><font color='black'>" + strJ[0] + "</font></td>";
                            }
                            else
                            {
                                strTd += "<td  align=center colspan=" + strJ[3] + "><font color='black'>" + strJ[0] + "</font></td>";
                            }


                        }

                        descStr.Add(strTd);

                    }
                    arr.Add(descStr);

                }
            }

            return arr;
        }

        #endregion




        //处理链接字符  例如  倒叙回去 





        ///****************************************************
        ///*函数名称: getTableSheme
        ///*功能描述: 倒叙回去
        ///*参数列表: 1.arraylist里存字符范型
        ///*作者    : 
        /// *创建日期: 2009/05
        ///  ************************************************  


        #region 倒叙回去
        public string getTableSheme(ArrayList arr)
        {
            int maxArr = 0;
            string strSplit = "";
            for (int i = 0; i < arr.Count; i++)
            {
                if ((arr[i] as List<string>).Count > maxArr)
                {
                    maxArr = (arr[i] as List<string>).Count;
                }
            }//得到最长的数

            for (int i = 0; i < maxArr; i++)//序列倒置
            {
                for (int j = 0; j < arr.Count; j++)
                {
                    if ((arr[j] as List<string>).Count > i)
                    {
                        strSplit += (arr[j] as List<string>)[i];
                    }

                }
                if (i == maxArr - 1)
                {
                    strSplit = strSplit + "</tr>";
                }
                else
                {
                    strSplit = strSplit + "</tr><tr  >";
                }

            }
            return strSplit;
        }


        #endregion


        ///****************************************************
        ///*函数名称: getStatNumber
        ///*功能描述: 得到统计最终结果
        ///*参数列表: 1.一级标题的sql记录   2.多级标题列表（为显示最终顺序）  
        ///*作者    : 
        /// *创建日期: 2009/05
        ///  ************************************************  
        ///  
        #region 得到统计最终结果
        public string getStatNumber(DataRow[] dr, ArrayList arr, string strShemeid, string nodeid, string belongOperateStr, string priView)//
        {
            string strShowTr = "";
            string sql = "";
            string sqlConnect = "";
            string sqlbeglongtable = "";
            string strTablename = "";
            string strLevel = "";
            string strAgg = "";//聚合函数中间量
            string tempAgg = "";//记录聚合函数中间量的值
            string belongOperate = "";//用户网系权限

            DataSet dsNode = new DataSet();//得到节点表的节点条件
            DataSet dsTemp = new DataSet();

            DataSet dsTotal = new DataSet();//全部记录
            DataTable dt = new DataTable();



            List<string> strTableType = new List<string>();  //记录  用来区别dsTotal的 table
            List<string> strTableWhere = new List<string>();  //记录  用来区别dsTotal的 table



            //    List<string> descStr = new List<string>();

            if (dr.Length != 0 && arr.Count != 0)
            {
                for (int i = 0; i < dr.Length; i++)//得到查询所要dt 放在ds里面
                {


                    sql = dr[i]["STATCONDITION"].ToString();
                    dt = oss.getValue(sql).Tables[0];
                    dt.TableName = dr[i]["LEVELCODE"].ToString();

                    strTableType.Add(dr[i]["LEVELCODE"].ToString());//
                    strTableWhere.Add(dr[i]["STATITEMID"].ToString());


                    dsTotal.Tables.Add(dt.Copy());
                    dt.Clear();
                    dsTemp.Clear();
                }

                sql = "select ID,NODEID,NODETYPE from com_statistics_scheme_node where id='" + strShemeid + "'";
                dsNode = oss.getValue(sql);

                for (int j = 0; j < dsNode.Tables[0].Rows.Count; j++)//节点条件行数
                {
                  //  strShowTr += "<td  align=center style='color:black'>" + dsNode.Tables[0].Rows[j]["NODEID"].ToString() + "</td>";
                    strShowTr += "<td  align=center style='color:black'>统计信息</td>";

                    for (int indexlike = 0; indexlike < arr.Count; indexlike++)//多级标题 记录
                    {
                        for (int indexDs = 0; indexDs < strTableType.Count; indexDs++) //ds里的dt个数
                        {
                            if (arr[indexlike].ToString().IndexOf(strTableType[indexDs]) != -1)  //根据levelcode 来判断
                            {
                                string[] temp = { "###" };
                                string[] tempArr = arr[indexlike].ToString().Split(temp, StringSplitOptions.None);
                                sqlConnect = tempArr[1].ToString();
                                strLevel = tempArr[2].ToString();
                                strAgg = tempArr[4].ToString();
                                strTablename = strTableType[indexDs];
                                sqlbeglongtable = strTableWhere[indexDs];
                                belongOperate = tempArr[5].ToString();


                                break;

                            }
                        }
                        if (priView == "1")
                        {
                            DataRow[] drcount;
                            if (sqlConnect != "" && strAgg != "stat,1")
                            {

                                sql = sqlConnect + " and " + dsNode.Tables[0].Rows[j]["NODETYPE"].ToString().ToUpper() + " LIKE '" + dsNode.Tables[0].Rows[j]["NODEID"].ToString().ToUpper() + "%'";
                            }
                            else
                            {
                                sql = "1=1";
                            }
                            drcount = dsTotal.Tables[strTablename].Select(sql);
                            string[] arrAgg = strAgg.Split(',');

                            if (dsNode.Tables[0].Rows[j]["NODEID"].ToString().IndexOf(nodeid.Replace("'", "")) != -1)
                            {
                             //   if (belongOperateStr.IndexOf("," + belongOperate + ",") != -1)权限控制
                                //{
                                    if (drcount.Length == 0)
                                    {
                                        strShowTr += "<td  align=center style='color:black'>0</td>";
                                    }
                                    else
                                    {

                                        if (arrAgg.Length > 2)
                                        {
                                            tempAgg = getAgg(drcount, arrAgg);
                                            strShowTr += "<td   align=center style='color:black' ><a href=# onclick=\"open('detailScheme.aspx?tablename=" + System.Web.HttpUtility.UrlEncode(sqlbeglongtable) + "&nodetype=" + System.Web.HttpUtility.UrlEncode(dsNode.Tables[0].Rows[j]["NODETYPE"].ToString().ToUpper()) + "&nodeid=" + System.Web.HttpUtility.UrlEncode(dsNode.Tables[0].Rows[j]["NODEID"].ToString().ToUpper()) + "&strLevel=" + strLevel + "&schemeid=" + strShemeid + " ','_blank' ,'top=40,left=150,toolbar=no,scrollbars=yes,location=no,directories=no,status=yes,menubar=no,resizable=yes')\" >" + tempAgg + "</a></td>";
                                        }
                                        else
                                        {
                                            strShowTr += "<td  align=center style='color:black' ><a href=# onclick=\"open('detailScheme.aspx?tablename=" + System.Web.HttpUtility.UrlEncode(sqlbeglongtable) + "&nodetype=" + System.Web.HttpUtility.UrlEncode(dsNode.Tables[0].Rows[j]["NODETYPE"].ToString().ToUpper()) + "&nodeid=" + System.Web.HttpUtility.UrlEncode(dsNode.Tables[0].Rows[j]["NODEID"].ToString().ToUpper()) + "&strLevel=" + strLevel + "&schemeid=" + strShemeid + " ','_blank' ,'top=40,left=150,toolbar=no,scrollbars=yes,location=no,directories=no,status=yes,menubar=no,resizable=yes')\" >" + drcount.Length + "</a></td>";
                                        }

                                    }
                               // }
                                //else
                                //{
                                //    strShowTr += "<td  align=center style='color:black'>--</td>";
                                //}
                            }
                        }
                        else
                        {
                            strShowTr += "<td  align=center style='color:black'>--</td>";
                        }
                      

                    }
                    // if (j == 0)
                    //  {
                    //   strShowTr += "<td  align=center style='font-size:20px;font-family: 楷体_GB2312;font-weight: bold;color:black'>" + dsNode.Tables[0].Rows[j]["NODEID"].ToString() + "</td>" + strShowTr;
                    //  }
                    if (j == dsNode.Tables[0].Rows.Count - 1)
                    {
                        strShowTr += "</tr>";
                    }
                    else
                    {
                        strShowTr += "</tr><tr  style=\"background-color:White\" >";
                    }



                }

            }
            dsNode.Clear();
            dsNode.Dispose();

            dsTotal.Clear();
            dsTotal.Dispose();

            dt.Clear();
            dt.Dispose();

            return "<tr  style=\"background-color:White\" >" + strShowTr;

        }
        #endregion

        /// <summary>
        /// 合计项目
        /// </summary>
        /// <param name="dr"></param>
        /// <param name="arr"></param>
        /// <returns></returns>
        ///
        #region 合计项目
        public string getAgg(DataRow[] dr, string[] arr)
        {
            int tempAgg = 0;
            int tempI = 0;
            if (dr.Length > 0)
            {
                for (int i = 0; i < dr.Length; i++)
                {
                    tempAgg = tempAgg + Convert.ToInt32(dr[i][arr[2].ToUpper()]);
                    tempI = i;
                }
                if (arr[1].ToUpper() == "AVG")
                {
                    tempAgg = tempAgg / tempI;
                }

            }
            else
            {
                tempAgg = 0;
            }
            return tempAgg.ToString();
        }

        #endregion
        public string getSchemeName(string schemeId)
        {
            DataSet ds = new DataSet();
            string sql = "select  ct.schemename as name from com_statistics_scheme_title  ct  where ct.id='" + schemeId + "'";
            string sName = "";
            ds = oss.getValue(sql);
            sName = ds.Tables[0].Rows[0]["name"].ToString();
            return sName;

        }

    }
    

}
